package com.example.caoh.controller.login;

import static com.example.caoh.utils.Result.ERROR;
import static com.example.caoh.utils.Result.SUCCESS;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.example.caoh.controller.BaseController;
import com.example.caoh.entity.SysUser;
import com.example.caoh.service.sys.SysResourcesService;
import com.example.caoh.service.sys.SysRoleService;
import com.example.caoh.utils.Const;
import com.example.caoh.utils.CookieUtil;
import com.example.caoh.utils.SessionUtil;

@Controller
public class LoginController extends BaseController{
	
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysResourcesService sysResourcesService;
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	    public Object submitLogin(String username, String password, HttpServletRequest request) {
			Map<String, Object> resultReturn = new HashMap<String, Object>();
	        try {
	            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
	            Subject subject = SecurityUtils.getSubject();
	            subject.login(token);
	            SysUser user = (SysUser) subject.getPrincipal();
	            SessionUtil.setUser(user);
				resultReturn.put("user", user);
				if (user.getRoleId() == null) {
//					SessionUtil.setMenu(sysMenuService.menuTreeData());
//					resultReturn.put("menu", sysMenuService.menuTreeData());
				} else {
					SessionUtil.setMenu(sysResourcesService.getMenuList(user.getRoleId(),true));
					resultReturn.put("menu", sysResourcesService.getMenuList(user.getRoleId(),true));
				}
				return SUCCESS("SUCCESS", resultReturn);
//	            jsonObject.put("msg", "登录成功");
//	            jsonObject.put("code", "1");
	        } catch (DisabledAccountException e) {
	            return ERROR(-1, HttpStatus.OK, "账户已被禁用");
	        } catch (AuthenticationException e) {
	            return ERROR(-1, HttpStatus.OK, "用户名或密码错误");
	        }
	        
	    }


	    @RequestMapping(value = "/login", method = RequestMethod.GET)
	    public String loginPage() {
	        return "login";
	    }

	    @RequestMapping(value = "/loginIndex", method = RequestMethod.GET)
	    public String loginSuccessMessage(HttpServletRequest request) {
	       
	        return "index";
	    }
	    
	    @RequestMapping(value = "/entity",method = RequestMethod.GET)
		@ResponseBody
		public final Object get() {
			try {
				Map<String, Object> result = new HashMap<String, Object>();
				result.put("menu", SessionUtil.getMenu());
				result.put("user", SessionUtil.getUser());
				return result;
			} catch (Exception e) {
				return ERROR(-1, HttpStatus.BAD_REQUEST, "系统错误");
			}
		}
	    

	    @RequestMapping(value = "/logout" ,method = RequestMethod.POST)
	    @ResponseBody
	    public Object loginout(HttpServletRequest request,HttpServletResponse response,HttpSession session) {
	    	Subject currentUser = SecurityUtils.getSubject();
//			String token = getToken(request);
	        session = request.getSession(true);
	        session.removeAttribute(Const.SESSION_USER);
	        currentUser.logout();
//			if (token != null) {
//				removeCommonCookie(request,response);
//				CookieUtil.removeCookie(token, request, response);
//				removeFromCache(token);
//			}
//			jsonObject.put("msg", "登出成功");
//            jsonObject.put("code", "1");
//            return jsonObject;
	        return SUCCESS("SUCCESS", "注销成功");
	    }
//	    
//	    /**
//		 * Desc
//		 * 
//		 * @param request
//		 * @return
//		 */
//		public String getToken(HttpServletRequest request) {
//			Cookie[] cookies = request.getCookies();
//			Cookie tokenCookie = null;
//			if (cookies.length != 0) {
//				for (int i = 0; i < cookies.length; i++) {
//					if (cookies[i].getName().equals("token")) {
//						tokenCookie = cookies[i];
//					}
//				}
//				if (tokenCookie == null)
//					return null;
//				return tokenCookie.getValue();
//			} else {
//				return "";
//			}
//		}
//		
//		/**
//		 * Desc 登出之后移除cookie信息
//		 * 
//		 * @param username
//		 * @param time
//		 * @param tokenid
//		 */
//		private void removeCommonCookie(HttpServletRequest request,HttpServletResponse response) {
//			Cookie[] cookies = request.getCookies();
//			for (int i = 0; i < cookies.length; i++) {
//				if (cookies[i].getName().equals("token")) {
//					Cookie newCookie = new Cookie("token", null);
//					newCookie.setPath("/");
//					newCookie.setMaxAge(0);
//					response.addCookie(newCookie);
//				}
//				if (cookies[i].getName().equals("username")) {
//					Cookie newCookie = new Cookie("username", null);
//					newCookie.setPath("/");
//					newCookie.setMaxAge(0);
//					response.addCookie(newCookie);
//				}
//				if (cookies[i].getName().equals("tml")) {
//					Cookie newCookie = new Cookie("tml", null);
//					newCookie.setPath("/");
//					newCookie.setMaxAge(0);
//					response.addCookie(newCookie);
//				}
//			}
//		}
		
		
}
